/*
 * @Descripttion: 
 * @version: 1.0.0
 * @Author: tb
 * @LastEditors: tb
 */
import axios, { AxiosResponse, AxiosRequestHeaders, InternalAxiosRequestConfig } from 'axios'
import { message } from 'ant-design-vue'
import router from '../router'

// 定义返回值类型
export interface Result<T = any> {
  code: number,
  msg: string,
  data: T
}

const instance = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 6*1000,
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  }
})

instance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    if (localStorage.getItem('token')) {
      (config.headers as AxiosRequestHeaders)['Tk-xs'] = localStorage.getItem('token') as string
    } else {
      router.replace({
        path: '/login'
      })
    }
    return config
  },
  (error: any) => {
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  (response: AxiosResponse) => {
    switch (response.data.code) {
      case 401:
        localStorage.clear()
        sessionStorage.clear()
        router.replace({
          path: '/login'
        })
        break;
      case 1001:
        message.error(response.data.msg)
        break
    }
    return response.data
  },
  (error: any) => {
    return Promise.reject(error)
  }
)

const http = {
  post<T = Result>(url:string, data?: object):Promise<T> {
    return instance.post(url, data)
  },
  get<T = Result>(url:string, params?: object):Promise<T> {
    return instance.get(url,{ params })
  },
  put<T = Result>(url:string, data?:object):Promise<T> {
    return instance.put(url, data)
  },
  delete<T = Result>(url:string, data?: object):Promise<T> {
    return instance.delete(url, data)
  },
  // 图片上传
  upload<T = Result>(url: string, params?: object): Promise<T> {
    return instance.post(url, params, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  }
}
export default http